package cn.demo.text.editor.strategy.menu.action;

import cn.demo.text.editor.constant.RunParam;
import cn.demo.text.editor.constant.Str;
import cn.demo.text.editor.strategy.format.process.Format;
import cn.demo.text.editor.strategy.format.process.FormatFactory;

import javax.swing.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class OpenAction implements Action {
    @Override
    public void operate(JTextArea jta) throws Exception {

        JFileChooser jfc = new JFileChooser();
        jfc.setDialogTitle(Str.PLEASE_SELECT_FILE);
        jfc.showOpenDialog(null);
        jfc.setVisible(true);

        File file = jfc.getSelectedFile();
        BufferedReader br = null;

        try {
            if (file == null) return;

            RunParam.context.put(Str.FILE_PATH, file.getAbsolutePath());

            FileReader fReader = new FileReader(file);
            br = new BufferedReader(fReader);

            StringBuilder jtaTextSb = new StringBuilder();
            int tmp;
            while ((tmp = br.read()) != -1) {
                jtaTextSb.append((char) tmp);
            }

            String jtaText = jtaTextSb.toString();

            Format format = FormatFactory.getFormat(file.getName().substring(file.getName().lastIndexOf(".")));
            String[] split = jtaText.split("\\r?\\n");
            StringBuilder tmpJtaTextSb = new StringBuilder();
            for (String line : split) {
                String analysis = format.analysis(Str.OPEN, line);
                tmpJtaTextSb.append(analysis).append(Str.Slash_R_Slash_N);
            }

            jtaText = tmpJtaTextSb.toString();

            jta.setText(jtaText);

        } finally {
            if (br != null) br.close();
        }
    }
}
